const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = 8082;

// 读取配置文件
let config;
try {
  const configPath = path.join(__dirname, '..', 'config.json');
  config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
} catch (error) {
  console.error('Error reading config file:', error);
  config = { storiesPath: './stories' };
}

// 启用CORS
app.use(cors());

// 静态文件服务 - 指向stories文件夹
const storiesPath = path.join(__dirname, '..', config.storiesPath);
app.use('/audio', '/usr/local/gxg/oneday/stories');

// 获取LRC文件内容
app.get('/api/lrc/:filename', (req, res) => {
  const filename = req.params.filename;
  const lrcPath = path.join(storiesPath, filename);
  
  try {
    if (fs.existsSync(lrcPath)) {
      const lrcContent = fs.readFileSync(lrcPath, 'utf8');
      res.json({ content: lrcContent });
    } else {
      res.status(404).json({ error: 'LRC file not found' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Error reading LRC file' });
  }
});

// 获取故事列表
app.get('/api/stories', (req, res) => {
  try {
    // 自动扫描stories文件夹中的mp3文件
    const files = fs.readdirSync(storiesPath);
    const mp3Files = files.filter(file => file.endsWith('.mp3'));
    
    const storyList = mp3Files.map(mp3File => {
      const baseName = path.basename(mp3File, '.mp3');
      const lrcFile = `${baseName}.lrc`;
      const lrcPath = path.join(storiesPath, lrcFile);
      
      // 检查对应的LRC文件是否存在
      const hasLrc = fs.existsSync(lrcPath);
      
      return {
        id: baseName,
        title: baseName, // 使用文件名作为标题
        description: hasLrc ? `故事: ${baseName}` : `故事: ${baseName} (无字幕)`,
        audioUrl: `/audio/${mp3File}`,
        lrcFile: hasLrc ? lrcFile : null
      };
    });
    
    res.json(storyList);
  } catch (error) {
    console.error('Error scanning stories directory:', error);
    res.status(500).json({ error: 'Error reading stories' });
  }
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', message: 'Story Player Server is running' });
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
  console.log(`Stories path: ${storiesPath}`);
  console.log(`API endpoints:`);
  console.log(`  - GET /api/health`);
  console.log(`  - GET /api/stories`);
  console.log(`  - GET /api/lrc/:filename`);
  console.log(`  - Static files: /audio/*`);
});